import { EditOutlined } from '@ant-design/icons';
import { Button, Input, Select, Modal, Form, message,Radio } from 'antd';
import { connect, FormattedMessage, formatMessage } from 'umi';
import React, { Component } from 'react';
import RegionSelect from '@/components/RegionSelect';
import styles from './BaseView.less';
import { getDefaultAvatarUrl } from '@/utils/default'
import { CircleAvatarUpload } from '@/components/Upload'

const { Option } = Select; // 头像组件 方便以后独立，增加裁剪之类的功能

const AvatarView = ({ avatar, dispatch }) => (
  <>
    <div className={styles.avatar_title}>
      <FormattedMessage id="common.avatar" defaultMessage="Avatar" />
    </div>
    <CircleAvatarUpload value={avatar} isCrop={true} onChange={data => {
      if (dispatch) {
        dispatch({
          type: 'user/update',
          payload: {
            avatarUrl: data
          },
        }).then(() => {
          dispatch({
            type: 'user/getMyInfo',
            payload: {
              avatarUrl: data
            },
          })
        })
      }
    }}></CircleAvatarUpload>
  </>
);

const validatorRegion = (_, value, callback) => {
  const { provinceId, cityId } = value;
  if (provinceId && !cityId) {
    callback('请输入城市!');
  }
  callback();
};


class BaseView extends Component {
  view = undefined;
  editUser = false;
  constructor(props) {
    super(props);
    this.state = {
      userNameModalVisible: false,
      usernameLengthLimit: "0/20"
    }

  }
  updateUsename = () => {
    const { dispatch, myDetail } = this.props;
    dispatch({
      type: 'user/updateUsername',
      payload: {
        username: this.state.username
      },
    }).then((success) => {
      if (success) {
        myDetail.username = this.state.username
        this.setState({
          userNameModalVisible: false
        })
      }
    })
  }

  updateUsenameConfirm = () => {
    if (!this.state.username) {
      message.error("用户名无变化")
      return;
    }
    Modal.warn({
      title: '修改用户名',
      content: `确认修改用户名为：${this.state.username}`,
      okText: '确认',
      onOk: (v) => {
        this.updateUsename();
        return Promise.resolve()
      }
    });
  }

  getAvatarURL() {
    const { myDetail } = this.props;

    if (myDetail) {
      if (myDetail.avatarUrl) {
        return myDetail.avatarUrl;
      }
    }
    const url = getDefaultAvatarUrl(myDetail.id)
    return url;
  }

  getViewDom = (ref) => {
    this.view = ref;
  };
  handleFinish = (form) => {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'user/update',
        payload: {
          ...form,
          ...form.region
        },
      }).then(() => {
        dispatch({
          type: 'user/getMyInfo'
        })
      })
    }
  };

  render() {
    const { myDetail } = this.props;
    if (!myDetail || !myDetail.id) {
      return '';
    }
    myDetail.region = {
      provinceId: myDetail.provinceId,
      cityId: myDetail.cityId
    }
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left}>
          <Form
            layout="vertical"
            onFinish={this.handleFinish}
            initialValues={myDetail}
            hideRequiredMark
          >
            <Form.Item
              name="id"
              label='ID'
            >
              {myDetail.id}
            </Form.Item>
            <Form.Item
              name="username"
              label={formatMessage({
                id: 'accountandsettings.basic.username',
              })}
            >
              {myDetail.username}  <Button onClick={() => {
                this.setState({
                  userNameModalVisible: true,
                  usernameLengthLimit: `${myDetail.username.length}/20`
                })
              }} type="link" icon={<EditOutlined />}></Button>
            </Form.Item>
            <Form.Item
              name="nickName"
              label={formatMessage({
                id: 'accountandsettings.basic.nickname',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage(
                    {
                      id: 'accountandsettings.basic.nickname-message',
                    },
                    {},
                  ),
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="gender"
              label={"性别"}
              rules={[
                {
                  required: true,
                  message: "请选着您的性别"
                },
              ]}
            >
              <Radio.Group>
                <Radio value={0}>女</Radio>
                <Radio value={1}>男</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="motto"
              label="一句话表达一下吧"
              rules={[
                {
                  message: "",
                },
              ]}
            >
              <Input.TextArea
                placeholder="一句话表达一下吧"
                maxLength={150}
                rows={3}
                className={styles.mottoClass}
              />
            </Form.Item>
            <Form.Item
              name="country"
              label={formatMessage({
                id: 'accountandsettings.basic.country',
              })}
            >
              <Select
                style={{
                  maxWidth: 220,
                }}
                defaultValue="China"
              >
                <Option value="China">中国</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="region"
              label={formatMessage({
                id: 'accountandsettings.basic.geographic',
              })}
              rules={[
                {
                  validator: validatorRegion,
                },
              ]}
            >
              <RegionSelect />
            </Form.Item>
            <Form.Item
              name="address"
              label={formatMessage({
                id: 'accountandsettings.basic.address',
              })}
              rules={[
                {
                  message: formatMessage(
                    {
                      id: 'accountandsettings.basic.address-message',
                    },
                    {},
                  ),
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item>
              <Button htmlType="submit" type="primary">
                <FormattedMessage
                  id="common.form.save"
                />
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className={styles.right}>
          <AvatarView avatar={this.getAvatarURL()} {...this.props} />
        </div>
        <Modal
          title="修改用户名"
          destroyOnClose
          centered
          closable
          onOk={this.updateUsenameConfirm}
          onCancel={() => {
            this.setState({
              userNameModalVisible: false
            })
          }}
          visible={this.state.userNameModalVisible}
        >
          <Input
            defaultValue={myDetail.username}
            placeholder="请输入用户名"
            onChange={(e) => {
              this.setState({
                username: e.target.value,
                usernameLengthLimit: `${e.target.value.length}/20`
              })
            }}
            maxLength={20}
            suffix={this.state.usernameLengthLimit}
          ></Input>
        </Modal>
      </div>
    );
  }
}

export default connect(({ user }) => ({
  myDetail: user.myDetail
}))(BaseView);
